package com.abc.robot01.retrofit

import com.abc.robot01.retrofit.bean.ApiResponse
import com.abc.robot01.retrofit.bean.ApiResponse2
import com.abc.robot01.retrofit.bean.Commodity
import com.abc.robot01.retrofit.bean.Condition
import com.abc.robot01.retrofit.bean.Condition2
import com.abc.robot01.retrofit.bean.Condition20
import com.abc.robot01.retrofit.bean.Condition3
import com.abc.robot01.retrofit.bean.Condition7
import com.abc.robot01.retrofit.bean.Condition70
import com.abc.robot01.retrofit.bean.Condition701
import com.abc.robot01.retrofit.bean.Condition8
import com.abc.robot01.retrofit.bean.Data
import com.abc.robot01.retrofit.bean.Data05
import com.abc.robot01.retrofit.bean.Data12345
import com.abc.robot01.retrofit.bean.Data3
import com.abc.robot01.retrofit.bean.Data5
import com.abc.robot01.retrofit.bean.Data789
import com.abc.robot01.retrofit.bean.Data9
import com.abc.robot01.retrofit.bean.DataItem
import com.abc.robot01.retrofit.bean.FetchDataRequest
import com.abc.robot01.retrofit.bean.FetchDataRequest2
import com.abc.robot01.retrofit.bean.FetchDataRequest9
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.LoginResponse
import com.abc.robot01.retrofit.bean.PaymentRequest
import com.abc.robot01.retrofit.bean.RenderPaymentRequest
import com.abc.robot01.retrofit.bean.RenderPaymentRequest2
import com.abc.robot01.retrofit.bean.RenderQueueData
import com.abc.robot01.retrofit.bean.RequestData
import com.abc.robot01.retrofit.bean.ResponseData
import com.abc.robot01.retrofit.bean.RoomData
import com.abc.robot01.retrofit.bean.SkyBoxData
import com.abc.robot01.retrofit.bean.TokenData
import com.abc.robot01.retrofit.bean.UserData
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
import java.util.concurrent.TimeUnit

interface RetrofitService {

    /**
     * 获取公司钱包余额
     */
    @GET("/companyPurse/getPurseAmount")
    suspend fun getPurseAmount(
        @Query("access_token") accessToken: String,
        @Query("companyId") companyId: String,
    ): ApiResponse<Double>

    /**
     * 首页配置
     */
    @GET("product/robot/homePageConfig")
    suspend fun getHomePage(
        @Query("robotId") robotID: String,
        @Query("companyId") companyId: String
    ): ApiResponse2<List<DataItem>>

    /**
     * Token
     */
    @POST("token/getRobotToken")
    suspend fun getToken(
        @Query("robotId") robotId: String,
    ): ApiResponse<TokenData>

    /**
     * 商品库
     */
    @POST("product/commodity/page")
    suspend fun getCompanyProduct(
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest2 = FetchDataRequest2()
    ): ApiResponse2<Data5>

    /**
     * ### 6、获取商品详情
     */
    @POST("/product/commodity/getById")
    suspend fun getProductById(
        @Query("id") id: String,
    ): ApiResponse<Commodity>

    /**
     * 获取公司的唤醒页配置
     */
    @GET("product/robot/wakeUpConfig")
    suspend fun wakeUpConfig(
        @Query("companyId") companyId: String,
    ): ResponseBody

    /**
     * 获取设计方案列表
     */
    @POST("designPackage/list")
    suspend fun getDesignPackages(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition>
    ): ResponseBody

    /**
     * 获取带识别结果的户型列表
     */
    @POST("housePlans/pageWithReadResult")
    suspend fun getHouseLayouts(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition2>
    ): ApiResponse<HouseLayoutData>

    /**
     * 获取指定户型图下自己的户型数据
     */
    @POST("housePlanData/pageCompanyByHousePlanId")
    suspend fun getHousePlanData(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Query("housePlanId") housePlanId: String,
        @Body request: FetchDataRequest9<Condition20> = FetchDataRequest9(Condition20())
    ): ResponseBody


    // data 字段的类
    data class HouseLayoutData(
        val totalPages: Int?,
        val total: Int,
        val list: List<HouseLayoutItem>,
        val locationTotal: Any? // 根据你的需求，可以进一步细化类型
    )

    // list 数组中的每个对象对应的类
    data class HouseLayoutItem(
        val id: String,
        val name: String?,
        var thumbnail: String?,
        val companyId: String?,
        val roomNum: Int,
        val hallNum: Int,
        val washroomNum: Int,
        val houseType: String?,
        val userId: String,
        val type: Int,
        val childCount: Int,
        val innerArea: Double,
        val pictureUrl: String,
        val source: String,
        val status: Int,
        val price: Double,
        val isValid: Int,
        val isUpper: Int,
        val createTime: String,
        val readResultDataId: String,
        //有没有户型数据
        val renderCount: Int
    )

    /**
     * 通过已有图片url识别
     */
    @POST("img-reading-service/saveReadingTask")
    suspend fun saveReadingTask(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Query("housePlansId") housePlansId: String,
        @Query("designPackageId") designPackageId: String,
        @Query("fileUrl") fileUrl: String,
        @Query("scale") scale: Int = 50,
    ): ApiResponse<String>

    /**
     * 上传图片后 轮询获取图片识别数据
     */
    @POST("autoDesign/getTaskStatus")
    suspend fun getTaskStatus(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Query("taskId") taskId: String,
        @Query("type") type: Int = 1,
    ): ResponseBody

    /**
     *  获取需要渲染的房间信息
     */
    @POST("renderPay/getRenderRooms")
    suspend fun getRenderRooms(
        @Query("access_token") accessToken: String,
        @Query("housePlansDataId") housePlansDataId: String,
        @Query("designPackageId") designPackageId: String,
    ): ApiResponse<List<RoomData>>

    /**
     *  获取渲染价格配置
     */
    @GET("designRenderPriceConfig/list")
    suspend fun designRenderPriceConfig(
        @Query("access_token") accessToken: String,
    ): ApiResponse<List<RenderQueueData>>

    /**
     *  获取待渲染的任务数
     */
    @GET("renderConfig/countWaitRenderConfig")
    suspend fun countWaitRenderConfig(
        @Query("access_token") accessToken: String,
    ): ApiResponse<Int>

    /**
     *  获取天空盒配置
     */
    @GET("designRenderSkyBox")
    suspend fun designRenderSkyBox(
        @Query("access_token") accessToken: String,
    ): ApiResponse<List<SkyBoxData>>

    /**
     * 充值支付,生产二维码
     */
    @POST("pay/prePay")
    suspend fun recharge(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Query("thirdPaymentType") thirdPaymentType: String,
        @Body request: PaymentRequest
    ): ApiResponse<Data789>

    /**
     * 保存户型数据(渲染支付前调用)
     */
    @POST("housePlanData")
    suspend fun housePlanData(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Body request: RenderPaymentRequest2
    ): ApiResponse<String?>

    /**
     * 渲染支付
     */
    @POST("pay/prePay")
    suspend fun renderPay(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String, // 当前操作的真实用户ID，非机器人ID
        @Query("companyId") companyId: String,
        @Query("thirdPaymentType") thirdPaymentType: String = "WECHAT_NATIVE",
        @Body request: RenderPaymentRequest
    ): ResponseData

    /**
     * wechatPay
     */
    @POST("pay/prePay")
    suspend fun wechatPay(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String, // 当前操作的真实用户ID，非机器人ID
        @Query("companyId") companyId: String,
        @Query("thirdPaymentType") thirdPaymentType: String = "WECHAT_NATIVE",
        @Body request: RenderPaymentRequest
    ): ApiResponse<Data12345>

    /**
     * 获取方案报价
     */
    @FormUrlEncoded
    @POST("product/quote/getByrenderConfigId")
    suspend fun getDesignPrices(
        @Field("renderConfigId") renderConfigId: String,
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String, // 当前操作的真实用户ID，非机器人ID
        @Query("companyId") companyId: String,
    ): ApiResponse2<PriceData>

    /**
     * 获取报价明细
     */
    @FormUrlEncoded
    @POST("product/quote/getDetailByrenderConfigId")
    suspend fun getDetails(
        @Field("renderConfigId") renderConfigId: String,
        @Field("id") id: Int,
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String, // 当前操作的真实用户ID，非机器人ID
        @Query("companyId") companyId: String,
    ): ResponseBody










    data class PriceData(
        val list: List<Any>,              // 空列表（可以根据实际内容更改类型）
        val zh: Zh                         // Zh 类
    )

    data class Zh(
        val yz: Double =0.0,                   // 硬装
        val yzzc: Double= 0.0,                 // 硬装主材
        val sf: Double = 0.0 ,                   // 税费
        val qtfy: Double = 0.0 ,                 // 其他费用
        val jczx: Double =0.0 ,                 // 基础装修
        val jjsp: Double = 0.0                  // 家居饰品
    )

    /**
     *  根据业务存储发起机器人端的异步任务
     *   // 业务数据类型(使用数字) 1 扫码登录及注册，2 校验超管权限，3 校验用户归属公司，
     * 	// 4 上传户型图， 5 分享，6 支付
     */
    @POST("product/robot/asyncTask")
    suspend fun asyncTask(
        @Body request: RequestData
    ): ApiResponse2<Data05?>

    /**
     *  机器人端生成微信小程序码
     */
    @POST("wechat/genMiniProgramQrCode")
    suspend fun genMiniProgramQrCode(
        @Query("type") type: String,
        @Query("sn") sn: String,
        @Query("rid") rid: String,
        @Query("access_token") accessToken: String,
    ): LoginResponse

    /**
     *  通过机器人端的随机ID获取小程序端操作结果（轮询）
     */
    @GET("product/robot/asyncTask")
    suspend fun pullAsyncTask(
        @Query("type") type: String,
        @Query("sn") sn: String,
        @Query("rid") rid: String,
        @Query("access_token") accessToken: String,
    ): ApiResponse2<Data3>

    /**
     *  分页获取客户列表
     */
    @POST("userOrderCustomer/page")
    suspend fun getCustomers(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition3>
    ): ApiResponse<Data9>

    /**
     *  分页获取客户渲染记录的列表
     */
    @POST("userOrderCustomer/detail/page")
    suspend fun getCustomerDetails(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition7>
    ):ApiResponse<Data963>

    /**
     *  渲染信息分页查询
     */
    @POST("renderConfig/listRenderTask")
    suspend fun getListRenderTask(
        @Query("access_token") accessToken: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition70>
    ):ApiResponse<RenderList>

    data class RenderList(
        val totalPages: Int? = null,
        val total: Int? = null,
        val list: List<RenderItem>? = null,
        val locationTotal: Int? = null
    )

    data class RenderItem(
        val id: String,
        val createUserId: String?,
        val updateUserId: String?,
        val createTime: String?,
        val updateTime: String?,
        val renderType: String?,
        val type: Int,
        val companyId: String?,
        val houseId: String?,
        val designId: String?,
        val vipLevel: String?,
        val resolutionLevel: Int,
        val textureLevel: Int,
        val status: Int,
        val configDetail: String?,
        val configDetails: String?,
        val thumbnail: String?,
        val waitNum: Int?,
        val waitTime: Int?,
        val name: String,
        val sourceUrl: String?,
        val fileSize: String?,
        val customerPhone: String?,
        val renderPayOrderId: String?,
        val audioUrl: String?,
        val version: String?,
        val showUrl: String?,
        val isRender: Boolean?,
        val url: String?,
        val robotName: String?,
        val robotId: String?,
        var endTime: String
    )

    data class Data963(
        val locationTotal: Int?,          // 如果为 null，使用 Int? 类型
        val total: Int,
        val list: List<Task>,
        val totalPages: Int?              // 如果为 null，使用 Int? 类型
    )

    data class Task(
        val id: String,
        val taskType: Int,
        val status: Int,
        val taskStatus: Int,
        val endTime: String,
        val designName: String,
        val url: String
    )

    /**
     * 字典
     */
    @GET("dict/getSysDicByType/{type}/")
    suspend fun getSysDicByType(
        @Path("type") type: String,
        @Query("access_token") accessToken: String,
    ): ApiResponse<List<HouseType>>

    /**
     * 获取贴图列表
     */
    @GET("/materialChannel/list/")
    suspend fun getMaterialList(
        @Query("access_token") accessToken: String,
        @Query("userId") userId: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition701>
    ): ResponseBody

    /**
     * 首页商品库
     */
    @POST("product/robot/homePageConfig/addedCommodity/page")
    suspend fun getHomePageCommodity(
        @Body request: FetchDataRequest
    ): ApiResponse<Data>

    @POST("robot/login")
    suspend fun login(
        @Query("sn") sn: String
    ): ApiResponse<UserData>

    /**
     * 获取渲染的预计完成时间
     */
    @GET("renderConfig/estimateFinishTime")
    suspend fun getEstimateFinishTime(
        @Query("access_token") accessToken: String,
        @Query("currentRenderQueueType") currentRenderQueueType: String
    ): ApiResponse<String>

    /**
     * 搜索公司下的户型图的创建者
     *
     * /housePlans/searchDesigner?companyId={companyId}
     */
    @POST("housePlans/searchDesigner")
    suspend fun getDesigners(
        @Query("access_token") accessToken: String,
        @Query("companyId") companyId: String,
        @Body request: FetchDataRequest9<Condition8> = FetchDataRequest9(Condition8())
    ): ApiResponse<DataInfo>

    data class DataInfo(
        val locationTotal: Any?,
        val total: Int,
        val list: List<UserInfo>,
        val totalPages: Any?
    )

    data class UserInfo(
        val id: String,
        val nickname: String,
        val companyId: Any?,
        val companyName: Any?
    )

    companion object {

        // 创建 LoggingInterceptor 并设置日志级别
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }

        private val client by lazy {
            OkHttpClient.Builder().addInterceptor(loggingInterceptor)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build()
        }

//
//        const val BASE_URL = "http://192.168.1.137:8080/"

//                            生产域名



//        const val BASE_URL = "https://dyapp.xmlights.com/"

        const val BASE_URL = "https://applet.xmlights.com/"

//        const val BASE_URL_H5 = "https://pcs-h5-dev.xmlights.com/"

        const val BASE_URL_H5 = "https://pcs-h5-official.xmlights.com/"

        private val retrofit: Retrofit by lazy {
            Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        val instance: RetrofitService by lazy {
            retrofit.create(RetrofitService::class.java)
        }
    }
}



